package org.opens.mybatisplus.handle;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.opens.mybatisplus.pojo.pub2enum.State;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/* 数据库中的数据类型 */
@MappedJdbcTypes(JdbcType.VARCHAR)

/* 转化后的数据类型 */
@MappedTypes(value = State.class)
public class StateTypeHandler extends BaseTypeHandler<State> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, State state, JdbcType jdbcType) throws SQLException {
        //加1修正jackson对枚举的转换是根据顺序进行的(从0开始), 但是数据库从1开始
        preparedStatement.setInt(i, state.getStateCode() + 1);
    }

    @Override
    public State getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        if (!resultSet.wasNull()) {
            return State.getUserStateByValue(value);
        }
        return null;
    }

    @Override
    public State getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String value = resultSet.getString(columnIndex);
        if (!resultSet.wasNull()) {
            return State.getUserStateByValue(value);
        }
        return null;
    }

    @Override
    public State getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String value = callableStatement.getString(columnIndex);
        if (!callableStatement.wasNull()) {
            return State.getUserStateByValue(value);
        }
        return null;
    }

}
